// 创建画布和上下文
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 600;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');

// 定义方块形状
const shapes = [
    [[1, 1, 1, 1]], // I
    [[1, 1], [1, 1]], // O
    [[0, 1, 0], [1, 1, 1]], // T
    [[1, 0, 0], [1, 1, 1]], // L
    [[0, 0, 1], [1, 1, 1]], // J
    [[1, 1, 0], [0, 1, 1]], // S
    [[0, 1, 1], [1, 1, 0]]  // Z
];

// 定义颜色
const colors = ['#00FFFF', '#FFD700', '#FF4500', '#00BFFF', '#8A2BE2', '#00FF00', '#FF00FF'];

// 初始化游戏状态
let board = Array.from({ length: 20 }, () => Array(10).fill(0));
let currentShape = getRandomShape();
let position = { x: 3, y: 0 };
let gameInterval;

// 获取随机形状
function getRandomShape() {
    const randomIndex = Math.floor(Math.random() * shapes.length);
    return { shape: shapes[randomIndex], color: colors[randomIndex] };
}

// 绘制方块
function drawShape(shape, x, y, color) {
    shape.forEach((row, i) => {
        row.forEach((cell, j) => {
            if (cell) {
                ctx.fillStyle = color;
                ctx.fillRect((x + j) * 30, (y + i) * 30, 30, 30);
                ctx.strokeStyle = '#000';
                ctx.strokeRect((x + j) * 30, (y + i) * 30, 30, 30);
            }
        });
    });
}

// 清除方块
function clearShape(shape, x, y) {
    shape.forEach((row, i) => {
        row.forEach((cell, j) => {
            if (cell) {
                ctx.clearRect((x + j) * 30, (y + i) * 30, 30, 30);
            }
        });
    });
}

// 检查碰撞
function checkCollision(shape, x, y) {
    for (let i = 0; i < shape.length; i++) {
        for (let j = 0; j < shape[i].length; j++) {
            if (shape[i][j]) {
                const newX = x + j;
                const newY = y + i;
                if (newX < 0 || newX >= 10 || newY >= 20 || board[newY]?.[newX]) {
                    return true;
                }
            }
        }
    }
    return false;
}

// 固定方块到棋盘
function placeShapeOnBoard(shape, x, y, color) {
    shape.forEach((row, i) => {
        row.forEach((cell, j) => {
            if (cell) {
                board[y + i][x + j] = color;
            }
        });
    });
}

// 清除满行
function clearLines() {
    let linesCleared = 0;
    board = board.reduce((acc, row) => {
        if (row.every(cell => cell !== 0)) {
            linesCleared++;
            return acc;
        }
        acc.push(row);
        return acc;
    }, []);
    while (board.length < 20) {
        board.unshift(Array(10).fill(0));
    }
    
    // 更新得分
    score += linesCleared * 10;
    updateScore();
    
    return linesCleared;
}

// 更新游戏状态
function updateGame() {
    clearShape(currentShape.shape, position.x, position.y);
    position.y++;

    if (checkCollision(currentShape.shape, position.x, position.y)) {
        position.y--;
        placeShapeOnBoard(currentShape.shape, position.x, position.y, currentShape.color);
        const linesCleared = clearLines();
        currentShape = getRandomShape();
        position = { x: 3, y: 0 };

        if (checkCollision(currentShape.shape, position.x, position.y)) {
            clearInterval(gameInterval);
            alert(`游戏结束! 清除了 ${linesCleared} 行`);
        }
    }

    drawShape(currentShape.shape, position.x, position.y, currentShape.color);
}

// 处理键盘事件
function handleKeyDown(event) {
    clearShape(currentShape.shape, position.x, position.y);

    switch (event.key) {
        case 'ArrowLeft':
            position.x--;
            break;
        case 'ArrowRight':
            position.x++;
            break;
        case 'ArrowDown':
            position.y++;
            break;
        case 'ArrowUp':
            currentShape.shape = rotateShape(currentShape.shape);
            break;
    }

    if (checkCollision(currentShape.shape, position.x, position.y)) {
        position.x++;
        if (checkCollision(currentShape.shape, position.x, position.y)) {
            position.x -= 2;
        }
        if (checkCollision(currentShape.shape, position.x, position.y)) {
            position.y--;
        }
    }

    drawShape(currentShape.shape, position.x, position.y, currentShape.color);
}

// 旋转方块
function rotateShape(shape) {
    const newShape = shape[0].map((_, colIndex) => shape.map(row => row[colIndex]));
    return newShape.reverse();
}

// 启动游戏
function startGame() {
    gameInterval = setInterval(updateGame, 500);
    window.addEventListener('keydown', handleKeyDown);
}

// 添加得分显示功能
let score = 0;
const scoreElement = document.createElement('div');
scoreElement.style.position = 'absolute';
scoreElement.style.top = '10px';
scoreElement.style.right = '10px';
scoreElement.style.color = '#000';
scoreElement.style.fontSize = '18px';
scoreElement.style.fontFamily = 'Arial';
scoreElement.style.backgroundColor = 'rgba(255, 255, 255, 0.7)';
scoreElement.style.padding = '5px 10px';
scoreElement.style.borderRadius = '5px';
document.body.appendChild(scoreElement);

function updateScore() {
    scoreElement.textContent = `得分: ${score}`;
}

// 添加键盘事件监听器，用于开始游戏
window.addEventListener('keydown', (event) => {
    if (event.key === 'Enter') {
        startGame();
    }
});

// 添加开始游戏的提示文本
ctx.fillStyle = '#000';
ctx.font = '20px Arial';
ctx.fillText('按 Enter 开始游戏', 50, 300);
